package com.dgut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dgut.mapper.AccountMapper;
import com.dgut.mapper.UserInfoMapper;
import com.dgut.pojo.Account;
import com.dgut.pojo.UserInfo;
import com.dgut.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Resource
    AccountMapper accountMapper;
    @Resource
    UserInfoMapper userInfoMapper;

    @Transactional
    @Override
    public void addAccount(Account account, UserInfo userInfo) throws Exception {
        accountMapper.insert(account);
        userInfo.setAccountId(account.getAccountId());
        userInfoMapper.insert(userInfo);
    }

    @Override
    public Page<Account> getAccountWithUserInfo(Page<Account> page, int isLocked,String order) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.ne("role","admin");
        if (isLocked!=-1){
            wrapper.eq("is_locked",isLocked);
        }
        if(StringUtils.isNotEmpty(order)){
            if(order.equals("desc")){
                wrapper.orderByDesc("create_time");
            }
            if(order.equals("asc")){
                wrapper.orderByAsc("create_time");
            }
        }
        return page.setRecords(accountMapper.getAccountWithUserInfo(page,wrapper));
    }

    @Transactional
    @Override
    public void updateIsLocked(int accountId, int isLocked) throws Exception{
        Account account = new Account();
        account.setAccountId(accountId);
        account.setIsLocked(isLocked);
        accountMapper.updateById(account);
    }

}
